<template>
  <div class="dcy-content">
    <!-- 查询条件 -->
    <Form ref="queryParams" :model="queryParams" inline :label-width="60" label-position="left">
      <FormItem label="用户组">
        <Input v-model="queryParams.userGroupName" clearable placeholder="请输入用户组"/>
      </FormItem>
      <FormItem :label-width="0" class="search-btn-mar">
        <Button icon="md-search"  type="primary" @click="refresh()">查询</Button>
        <Button icon="md-refresh"  type="primary" @click="reset()">重置</Button>
        <Button icon="md-add" type="primary"  @click="addUser()">添加</Button>
        <Button icon="md-add" type="primary"  @click="removeBatch()" :disabled="delBtnDisabled">删除</Button>
      </FormItem>
    </Form>

    <!-- 表格 -->
    <dcy-table
      ref="dcyTable"
      unique-id="userGroupId"
      :query-params="queryParams"
      :url="url"
      @table-select-val="selectVal"
      :columns="columns">
      <template slot-scope="{ row, index }" slot="action">
        <a @click="update(row)">修改</a>
        <Divider type="vertical"/>
        <a @click="remove(row)">删除</a>
        <Divider type="vertical"/>
        <a @click="authRole(row)">授权角色</a>
      </template>
    </dcy-table>

    <!-- 添加表单 -->
    <Modal
      v-model="dialogShow"
      :title="dialogTitle"
      :mask-closable="false"
      @on-cancel="handleReset('form')">
      <Form ref="form" :model="form" :rules="rules" :label-width="80">
        <FormItem label="用户组名" prop="userGroupName">
          <Input v-model="form.userGroupName" placeholder="请输入用户组名"/>
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
        </FormItem>
      </Form>
      <!-- 自定义按钮组 -->
      <div slot="footer">
        <Button type="text"  @click="handleReset('form')">取消</Button>
        <Button type="primary"  @click="handleSubmit('form')">确认</Button>
      </div>
    </Modal>

    <!-- 授权角色-->
    <Modal
      v-model="dialogAuthRoleShow"
      title="授权角色"
      :mask-closable="false"
      @on-ok="saveAuthRole"
      @on-cancel="cancelAuthRoleDialog">
      <Transfer
        v-if="dialogAuthRoleShow"
        filterable
        :data="roleList"
        :titles="['角色列表','已授权角色']"
        :target-keys="targetKeys"
        :filter-method="filterMethod"
        @on-change="handleRoleChange"></Transfer>
    </Modal>
  </div>
</template>

<script>
    import DcyTable from '@/components/dcy/dcy-table'
    import {addGroup, deleteBatchGroupById, deleteGroupById, updateGroup} from '@/api/admin/group'
    import {noticeError, noticeSuccess} from '@/libs/notice'
    import {getRoleAllList} from "../../api/admin/role";
    import {getAuthRoleListByUserGroupId, saveAuthGroupRole} from "../../api/admin/group";

    export default {
        name: 'group-manage',
        components: {DcyTable},
        data() {
            return {
                url: '/admin-service/group/page',
                columns: [
                    {title: '用户组名', key: 'userGroupName', align: 'center'},
                    {title: '操作', slot: 'action', align: 'center'}
                ],
                queryParams: {},
                dialogShow: false,
                dialogAuthRoleShow: false,
                delBtnDisabled: true,
                ids: [],
                dialogTitle: '添加用户组',
                form: {},
                rules: {
                    userGroupName: [this.$ruler('用户组名')]
                },
                userGroupId:null,
                roleList:[],
                targetKeys:[],
            }
        },
        methods: {
            /**
             * 刷新
             */
            refresh() {
                // 清空选中状态
                this.$refs.dcyTable.selectAll(false);
                this.$refs.dcyTable.refresh()
            },
            /**
             * 重置搜索条件
             */
            reset() {
                this.queryParams = {}
            },
            /**
             * 修改弹出框
             * @param row
             */
            update(row) {
                this.form = {...row};
                this.dialogTitle = '修改用户组';
                this.dialogShow = true
            },
            /**
             * 添加弹出框
             */
            addUser() {
                this.dialogTitle = '添加用户组';
                this.dialogShow = true
            },
            /**
             * 批量删除
             */
            removeBatch() {
                this.$Modal.confirm({
                    title: '您确认删除所选内容吗？',
                    onOk: () => {
                        deleteBatchGroupById(this.ids).then(res => {
                            if (res.data) {
                                noticeSuccess('del')
                            } else {
                                noticeError('del')
                            }
                            this.refresh()
                        })
                    }
                })
            },
            /**
             * 提交表单
             * @param name
             */
            handleSubmit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        if (this.dialogTitle === '添加用户组') {
                            addGroup(this.form).then(res => {
                                if (res.data) {
                                    noticeSuccess('add')
                                } else {
                                    noticeError('add')
                                }
                                this.cancelDialogAndRefresh()
                            })
                        } else {
                            updateGroup(this.form).then(res => {
                                if (res.data) {
                                    noticeSuccess('upd')
                                } else {
                                    noticeError('upd')
                                }
                                this.cancelDialogAndRefresh()
                            })
                        }
                    }
                })
            },
            /**
             * 行内删除
             * @param row
             */
            remove(row) {
                this.$Modal.confirm({
                    title: '您确认删除这条内容吗？',
                    onOk: () => {
                        deleteGroupById(row.userGroupId).then(res => {
                            if (res.data) {
                                noticeSuccess('del')
                            } else {
                                noticeError('del')
                            }
                            this.refresh()
                        })
                    }
                })
            },
            /**
             * 重置表单
             * @param name
             */
            handleReset(name) {
                this.form = {};
                this.dialogShow = false;
                this.$refs[name].resetFields()
            },
            /**
             * 关闭弹出框 和 刷新表格
             */
            cancelDialogAndRefresh() {
                // 清空表单
                this.handleReset('form');
                // 刷新表格
                this.refresh()
            },
            /**
             * 点击每一行的checkbox
             */
            selectVal(ids) {
                this.ids = ids;
                this.delBtnDisabled = !this.ids.length
            },
            /**
             * 授权角色
             * @param row
             */
            authRole(row) {
                this.userGroupId = row.userGroupId;
                this.dialogAuthRoleShow = true;
                getRoleAllList().then(res => {
                    if (res.success) {
                        let roleList = [];
                        res.data.forEach(e => {
                            let role = {
                                key: e.roleId,
                                label: e.roleName,
                                disabled: e.roleStatus === '1'
                            };
                            roleList.push(role);
                        });
                        this.roleList = roleList;
                    }
                });
                getAuthRoleListByUserGroupId(this.userGroupId).then(res => {
                    this.targetKeys = res.data.map(e => e.roleId);
                })
            },
            /**
             * 保存授权角色
             */
            saveAuthRole() {
                let userGroupRoleDTO = {
                    userGroupId: this.userGroupId,
                    roleIds: this.targetKeys
                };
                saveAuthGroupRole(userGroupRoleDTO).then(res => {
                    if (res.data) {
                        noticeSuccess('d')
                    } else {
                        noticeError('d')
                    }
                    // 刷新表格
                    this.refresh()
                })
            },
            /**
             * 关闭授权角色弹出框
             */
            cancelAuthRoleDialog() {
                this.dialogAuthRoleShow = false;
            },
            handleRoleChange(newTargetKeys) {
                this.targetKeys = newTargetKeys;
            },
            filterMethod(data, query){
                return data.label.indexOf(query) > -1;
            },
        }
    }
</script>

<style scoped>

</style>
